const {query} = require("./db");
const http = require("http");
const {URL} = require("url");
const formidable = require("formidable");
http.createServer((req,res)=>{
    let urlObj = new URL(req.url,"http://192.168.174.166:3000")
    let routes = {
        "POST":[
            {pathname:"/upload",callback:upload}
        ],
        "GET":[
            {pathname:"/sellLog",callback:sellLog},
            {pathname:"/dOrder", callback:dOrder},
            {pathname:"/rentDetail",callback:rentDetail},
            {pathname:"/publishtoBuy",callback:publishtoBuy},
            {pathname:"/thingDetail",callback:thingDetail},
            {pathname:"/buyLog",callback:buyLog},
            {pathname:"/rentLog",callback:rentLog},
            {pathname:"/lowerRent",callback:lowerRent}
        ]
    }
    let route = routes[req.method].filter(item=> item.pathname == urlObj.pathname)//找对应类型
    if(route[0]){
        route[0].callback(req,res);
    }

}).listen(3000);

//发布商品
async function upload(req,res){
    let sql = "insert into sell_buy(name,price,date,image) values(name,price,date,image)";
    await query(sql,[]);
}
//出售记录
async function sellLog(req,res){
    let sql = "select name,price from sell_buy";
    const results = await query(sql,[])
    res.end(JSON.stringify(results));
}
//订单详情
async function dOrder(req,res){
    let sql = "select name,price,b_type,pay_method,time,totalNum,income from d_order";
    const results = await query(sql,[]);
    res.end(JSON.stringify(results));
}
//租赁详情
async function rentDetail(req,res){
    let sql = "select time,type,name,pay_method,rent_price,rent_day,cash_pledge from rent_d";
    const results = await query(sql,[]);
    res.end(JSON.stringify(results));
}
//发布求购
async function publishtoBuy(req,res){
    let sql = "select describe,price,num,totalMoney,img from publish_req";
    const results = await query(sql,[]);
    res.end(JSON.stringify(results));
}
//物品详情
async function thingDetail(req,res){
    let sql = "select name,price from sell_buy";
    const results = await query(sql,[]);
    res.end(JSON.stringify(results));
}
//购买记录
async function buyLog(req,res){
    let sql = "select name,price from sell_buy";
    const results = await query(sql,[]);
    res.end(JSON.stringify(results));
}
//租赁记录
async function rentLog(req,res){
    let sql = "select name,rent_price,rent_day,cash_pledge from rent_log";
    const results = await query(sql,[]);
    res.end(JSON.stringify(results));
}
//低价租
async function lowerRent(req,res){
    let sql = "select short,long from lower_rent";
    const results = await query(sql,[]);
    res.end(JSON.stringify(results));
}